const SparkMD5 = require('spark-md5')
module.exports = (options, app) => {
    return async (ctx, next) => {
      const data = JSON.parse(JSON.stringify(ctx.request.method === 'GET' ? ctx.query : ctx.request.body))

      const { st, sg } = ctx.headers
      const errorMsg = process.env.NODE_ENV === 'development' ? {
        stEmpty: '缺少签名参数 st',
        stError: '签名错误 [st]',
        sgEmpty: '缺少签名参数 sg',
        sgError: '签名错误 [sg]'
      } : {
        stEmpty: '系统错误',
        stError: '系统错误',
        sgEmpty: '系统错误',
        sgError: '系统错误',
      }

      if (!st) {
        ctx.body = {
            code: 60001,
            msg: errorMsg.stEmpty,
            data: {}
        }
        return
      }

      const currentTimestamp = Date.parse(new Date())
      if (currentTimestamp < st || currentTimestamp - st > 10000) {
        ctx.body = {
            code: 60002,
            msg: errorMsg.stError,
            data: {}
        }
        return
      }
      if (!sg) {
        ctx.body = {
            code: 60001,
            msg: errorMsg.sgEmpty,
            data: {}
        }
        return
      }

      const secret = app.config.secret

      data.secret = secret
      data.st = st
      const keys = Object.keys(data).sort()
      const signJoin = keys.map(k => data[k]).join('|')
      const sign = SparkMD5.hash(signJoin)

      if (sign !== sg) {
        ctx.body = {
            code: 60002,
            msg: errorMsg.sgError,
            data: {
                correct: process.env.NODE_ENV === 'development' ? `${sign}|${app.config.secret}` : ''
            }
        }
        return
      }

      console.log(signJoin, sign, process.env)
      
      
      await next()
    }
  }